package com.governtalk.backend.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.governtalk.backend.service.CozeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CozeChatServiceImpl implements CozeChatService {

    @Value("${ai.coze.api-key:default-api-key}")
    private String apiKey;

    @Value("${ai.coze.bot-id:default-bot-id}")
    private String botId;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void sendImageChatToCoze(String question, String fileId, Long userId, SseEmitter emitter) {
        System.out.println("=== 开始发送带图片的对话到Coze ===");
        System.out.println("问题: " + question);
        System.out.println("文件ID: " + fileId);
        System.out.println("用户ID: " + userId);

        try {
            // 构建Coze v3对话请求
            Map<String, Object> request = new HashMap<>();
            request.put("bot_id", botId);
            request.put("user_id", userId.toString());
            request.put("stream", true);

            // 构建消息
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", question);
            message.put("content_type", "text");
            messages.add(message);

            // 添加图片消息
            Map<String, Object> imageMessage = new HashMap<>();
            imageMessage.put("role", "user");
            imageMessage.put("content", fileId);
            imageMessage.put("content_type", "file");
            messages.add(imageMessage);

            request.put("messages", messages);

            // 发送请求
            sendChatRequest(request, emitter);

        } catch (Exception e) {
            System.err.println("❌ 发送带图片对话失败: " + e.getMessage());
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI图片分析失败: " + e.getMessage()));
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
            }
            emitter.completeWithError(e);
        }
    }

    @Override
    public void sendFileContentChatToCoze(String question, String fileContent, Long userId, SseEmitter emitter) {
        System.out.println("=== 开始发送基于文件内容的对话到Coze ===");
        System.out.println("问题: " + question);
        System.out.println("文件内容长度: " + fileContent.length());
        System.out.println("用户ID: " + userId);

        try {
            // 构建Coze v3对话请求
            Map<String, Object> request = new HashMap<>();
            request.put("bot_id", botId);
            request.put("user_id", userId.toString());
            request.put("stream", true);

            // 构建消息
            List<Map<String, Object>> messages = new ArrayList<>();
            
            // 添加文件内容消息
            Map<String, Object> fileMessage = new HashMap<>();
            fileMessage.put("role", "user");
            fileMessage.put("content", fileContent);
            fileMessage.put("content_type", "text");
            messages.add(fileMessage);
            
            // 添加用户问题消息
            Map<String, Object> questionMessage = new HashMap<>();
            questionMessage.put("role", "user");
            questionMessage.put("content", question);
            questionMessage.put("content_type", "text");
            messages.add(questionMessage);

            request.put("messages", messages);

            // 发送请求
            sendChatRequest(request, emitter);

        } catch (Exception e) {
            System.err.println("❌ 发送基于文件内容的对话失败: " + e.getMessage());
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI文件内容分析失败: " + e.getMessage()));
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
            }
            emitter.completeWithError(e);
        }
    }

    @Override
    public void sendTextChatToCoze(String question, Long userId, SseEmitter emitter) {
        System.out.println("=== 开始发送文本对话到Coze ===");
        System.out.println("问题: " + question);
        System.out.println("用户ID: " + userId);

        try {
            // 构建Coze v3对话请求
            Map<String, Object> request = new HashMap<>();
            request.put("bot_id", botId);
            request.put("user_id", userId.toString());
            request.put("stream", true);

            // 构建消息
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", question);
            message.put("content_type", "text");
            messages.add(message);

            request.put("messages", messages);

            // 发送请求
            sendChatRequest(request, emitter);

        } catch (Exception e) {
            System.err.println("❌ 发送文本对话失败: " + e.getMessage());
            e.printStackTrace();
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("AI文本分析失败: " + e.getMessage()));
            } catch (IOException ioException) {
                System.err.println("发送错误信息失败: " + ioException.getMessage());
            }
            emitter.completeWithError(e);
        }
    }

    private void sendChatRequest(Map<String, Object> request, SseEmitter emitter) throws Exception {
        URL url = new URL("https://api.coze.cn/open_api/v3/chat");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "text/event-stream");
        connection.setDoOutput(true);

        // 发送请求数据
        String jsonRequest = objectMapper.writeValueAsString(request);
        System.out.println("Coze对话请求: " + jsonRequest);

        try (OutputStream outputStream = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes(StandardCharsets.UTF_8);
            outputStream.write(input, 0, input.length);
        }

        // 读取流式响应
        int responseCode = connection.getResponseCode();
        System.out.println("Coze对话响应码: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {

                String line;
                StringBuilder fullAnswer = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    System.out.println("收到流式数据: " + line);

                    if (line.startsWith("event:")) {
                        String eventType = line.substring(6).trim();
                        System.out.println("事件类型: " + eventType);

                        // 读取下一行的data
                        if ((line = reader.readLine()) != null && line.startsWith("data:")) {
                            String data = line.substring(5).trim();
                            System.out.println("事件数据: " + data);

                            if ("conversation.message.delta".equals(eventType)) {
                                // 处理流式消息内容
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    if (dataNode.has("role") && "assistant".equals(dataNode.get("role").asText())) {
                                        String content = "";
                                        
                                        if (dataNode.has("content") && !dataNode.get("content").asText().isEmpty()) {
                                            content = dataNode.get("content").asText();
                                        } else if (dataNode.has("reasoning_content")) {
                                            content = dataNode.get("reasoning_content").asText();
                                        }
                                        
                                        if (!content.isEmpty()) {
                                            fullAnswer.append(content);
                                            System.out.println("发送消息片段: " + content);
                                            
                                            emitter.send(SseEmitter.event()
                                                .name("message")
                                                .data(content));
                                        }
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析消息事件失败: " + e.getMessage());
                                }
                            } else if ("conversation.message.completed".equals(eventType)) {
                                // 消息完成
                                try {
                                    JsonNode dataNode = objectMapper.readTree(data);
                                    if (dataNode.has("content") && dataNode.has("role") && 
                                        "assistant".equals(dataNode.get("role").asText())) {
                                        String completeContent = dataNode.get("content").asText();
                                        System.out.println("发送完整消息: " + completeContent);
                                        
                                        emitter.send(SseEmitter.event()
                                            .name("message")
                                            .data(completeContent));
                                    }
                                } catch (Exception e) {
                                    System.err.println("解析完成消息失败: " + e.getMessage());
                                }
                                
                                emitter.send(SseEmitter.event()
                                    .name("complete")
                                    .data("AI分析完成"));
                                emitter.complete();
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    errorResponse.append(line);
                }
                String errorBody = errorResponse.toString();
                System.err.println("Coze对话错误响应: " + errorBody);
                throw new RuntimeException("Coze对话请求失败，响应码: " + responseCode + ", 响应: " + errorBody);
            }
        }
    }
}
